package com.cuit.service.impl;

import com.cuit.entity.User;
import com.cuit.mapper.LoginUserMapper;
import com.cuit.mapper.UserMapper;
import com.cuit.service.LoginUserService;
import com.cuit.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LoginUserServiceImpl implements LoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(String username, String password) {
        // 1. 根据用户名和密码查询用户信息
       User user = loginUserMapper.login(username,password);
       log.info("用户名：{}，密码：{}",username,password);
        // 2. 检查用户是否存在
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 3. 生成JWT
        return JwtUtil.getToken(username);
    }

    /**
     * 用户注册方法
     *
     * @param username 用户名
     * @param password 密码
     * @return 注册成功的用户对象
     * @throws RuntimeException 如果用户名已存在，则抛出运行时异常
     */
    @Override
    public User register(String username, String password) {
        // 检查用户名是否已存在
        User user = userMapper.findByUsername(username,password);
        // 如果用户已存在，则抛出异常
        if(user != null){
            throw new RuntimeException("用户名已存在");
        }
        // 注册新用户
        loginUserMapper.register(username,password);
        // 返回新注册的用户对象
        return userMapper.findByUsername(username,password);
    }
}
